﻿using CoreCms.Net.Caching.Configuration;
using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoreCms.Net.Caching
{
    /// <summary>
    /// FreeRedis 集群客户端
    /// </summary>
  public class FreeRedisClient
    {
        private static Dictionary<string, RedisClient> _cacheClient = new Dictionary<string, RedisClient>();

        public static void InitFreeRedisClient(List<RedisOption> redisOptionsList)
        {
            foreach(var op in redisOptionsList)
            {
                if (_cacheClient.ContainsKey(op.Name)){
                    throw new ArgumentNullException("redis配置名称重复");
                }
                if (string.IsNullOrEmpty(op.ServerAddress)){
                    throw new ArgumentNullException("redis-serverAddress配置为空");
                }
                var serverAddressList = GetConnectionStringBuilders(op.ServerAddress);
                var sentinelAddressList = GetConnectionStringBuilders(op?.SentinelAddress);
                RedisClient r = null;
                switch (op.Mode)
                {
                    case RedisMode.Cluster:
                        r = new RedisClient(serverAddressList);
                        break;
                    case RedisMode.Sentinel:
                        r = new RedisClient(op.ServerAddress, op.SentinelAddress.Split(';'), true);
                        break;
                    case RedisMode.Pooling:
                        r = new RedisClient(op.ServerAddress, sentinelAddressList);
                        break;
                    default:
                        r = new RedisClient(serverAddressList, null);
                        break;
                }
             
                r.Serialize = obj => JsonConvert.SerializeObject(obj);
                r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
                //r.Notice += (s, e) => Trace.WriteLine(e.Log);
                _cacheClient.Add(op.Name, r);
            }
        }

        private static ConnectionStringBuilder[] GetConnectionStringBuilders(string serverAddress)
        {
            List<ConnectionStringBuilder> list = new List<ConnectionStringBuilder>();
            if (!string.IsNullOrEmpty(serverAddress))
            {
                var sepAddress = serverAddress.Split(";");
                foreach (var address in sepAddress)
                {
                    list.Add(ConnectionStringBuilder.Parse(address));
                }
            }
            return list.ToArray();
        }

        public static RedisClient GetFreeRedisClient(string name = null)
        {
            if (string.IsNullOrEmpty(name))
            {
                return _cacheClient.FirstOrDefault().Value;
            }
            return _cacheClient[name];
        }
    }
}
